﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Depts;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Depts
{
    public class AddDeptCommandHandler : IRequestHandler<AddDeptCommand, APIResult<int>>
    {
        IBaseRepository<Dept> dRep;
        ILogger<AddDeptCommandHandler> logger;

        public AddDeptCommandHandler(IBaseRepository<Dept> dRep, ILogger<AddDeptCommandHandler> logger)
        {
            this.dRep = dRep;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddDeptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查部门名称是否已存在
                var dept = await dRep.GetAsync(x => x.DeptName == request.DeptName);
                if (dept != null) 
                {
                    return new APIResult<int>
                    {
                        Code=StatusEnumCode.Fail,
                        Message= "部门名称已存在",
                        Data=0
                    };
                }
                // 创建新部门
                var newDept = new Dept
                {
                    DeptName = request.DeptName,
                    ParentId= request.ParentId,
                    DeptStatus=1,//默认部门状态为启用
                    DeptNumber=100,//默认成员数量是100
                    UserId= request.UserId,
                    DeptDesc=request.DeptDesc,
                    UpdTime=DateTime.Now,//默认更新时间是当前时间
                    IsDel=false
                };
                // 添加角色到数据库
                await dRep.AddAsync(newDept);
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "添加部门成功",
                    Data = 1
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
